package com.ang.io.file;

import com.ang.io.stream.InputStreamDemo;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;

/**
 * @author ssang
 * @date 2023-04-19 17:39
 */
public class FileDemo {

    public static void main(String[] args) {
        FileDemo t = new FileDemo();
        t.test01();
    }

    /**
     *  获取文件所在的目录
     */
    public void test01(){
        String fileName = "template.docx";
        //获取resource文件
        URL url = this.getClass().getClassLoader().getResource(fileName);

        //获取文件全路径
        String fileNamePath = url.getPath();
        System.out.println(fileNamePath);

        //获取文件流
        File file = new File(fileNamePath);

        //获取父文件夹
        String dir = file.getParent();
        System.out.println(dir);
    }

    /**
     * File 转换为 MultipartFile
     * 注意指定文件类型："application/pdf"，按需指定
     */
    public static MultipartFile fileToMultipartFile(File file) {
        MultipartFile result = null;
        if (null != file) {
            try (FileInputStream input = new FileInputStream(file)) {
                result = new MockMultipartFile(file.getName().concat("temp"), file.getName(), "application/pdf", input);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
